﻿// Based on sample class for Copying and Pasting HTML fragments to and from the clipboard.
//
// Mike Stall. http://blogs.msdn.com/jmstall
using System;
using System.Diagnostics;

using System.Windows.Forms;

using System.Collections.Generic;
using System.Text;
using System.IO;

using System.Threading;

using System.Runtime.CompilerServices;

/// <summary>
/// Helper class to decode HTML from the clipboard.
/// See http://blogs.msdn.com/jmstall/archive/2007/01/21/html-clipboard.aspx for details.
/// </summary>
class TextClipboard
{
    static private string ms_clipboardText;
    static private string ms_textForClipboard;

    [MethodImplAttribute(MethodImplOptions.Synchronized)]
    static public string FromClipboard()
    {
        System.Threading.Thread myThread = new System.Threading.Thread(GetClipboardText);
        myThread.SetApartmentState(System.Threading.ApartmentState.STA);
        myThread.Start();
        myThread.Join();

        var retrievedText = ms_clipboardText;
        ms_clipboardText = null;
        return retrievedText;
    }

    public static void GetClipboardText()
    {
        ms_clipboardText = Clipboard.GetText(TextDataFormat.Text);
    }

    [MethodImplAttribute(MethodImplOptions.Synchronized)]
    public static void CopyToClipboard(string textForClipboard)
    {
        ms_textForClipboard = textForClipboard;
        System.Threading.Thread myThread = new System.Threading.Thread(CopyToClipboardSTA);
        myThread.SetApartmentState(System.Threading.ApartmentState.STA);
        myThread.Start();
        myThread.Join();
        ms_textForClipboard = null;
    }

    public static void CopyToClipboardSTA()
    {
        CopyToClipboardAPICall(ms_textForClipboard);
    }

    public static void CopyToClipboardAPICall(string data)
    {
        Clipboard.Clear();
        Clipboard.SetText(data, TextDataFormat.Text);
    }

}